<?php

/**
 * Displays the media gallery addition page
 */
function kgallery_tab($node, $type=NULL) { 
  $output.= drupal_get_form('_add_media', $node);	  
  print theme('kw_iframe_content', t('Attach files'), $output);
}

/**
 */
function _add_media($state, $node) {
  include_once(drupal_get_path('module', 'kentry').'/kentry.admin.inc');
  $field = _kentry_upload_field($node);
  $form['node'] = array('#type' => 'value', '#value' => $node);
  $node->cached = false;
  $node->chn = _kentry_values($node);  # Bypass the cached values
  $form['_auto'] = array(
    '#title' => t('From the Internet'),
    '#type' => 'textarea',
    '#description' => t('Add URLs of publicly available pictures and video on the Internet. '.
                        'Put one URL per line. A URL starts with <i>http://</i>.'),
    '#default_value' => $node->chn[$field->kfid]->value, 
  );

  $form['field_id'] = array('#type'=>'hidden', '#value'=>$field->kfid);
  $form['other']['vid'] = array('#type'=>'hidden', '#value'=>$node->vid);
  $form['other']['nid'] = array('#type'=>'hidden', '#value'=>$node->nid);
  $form['media'] = array(
    '#type'=>'fieldset', 
    '#title'=>t('Attach files from kasahorow Gallery'),
    '#collapsible' => 1,
    '#collapsed' => False,
    '#tree' => True,
  );
  $selected = _kgallery_node_selection($node->vid);
  $form['media']['mids'] = array(
    '#type'=>'select',
    '#title'=>t('Gallery').' ('.sizeof($selected).' selected)',
    '#multiple'=>TRUE,
    '#default_value' => $selected,
    '#options'=>_kgallery_load($node->vid),
    '#description' => t('Select existing files to be attached to this node.').
                      ' '.l('Manage', 'admin/content/kw/kgallery')
  );
  $form['iso'] = array('#type' => 'hidden', '#value' => $node->iso);
  $form['field_type'] = array('#type' => 'hidden', '#value' => 'node');
  $form['submit'] = array('#type'=>'submit', '#value'=>t('Save changes'));
  return $form;
}

/**
 * Form submission processing
 */
function _add_media_submit($state, &$values){
  global $user;
  $v = $values['values'];
  //Internet links
  _kentry_field_save($v['field_id'], $v['vid'], $v['_auto']);
  $v['node']->files = $v['files'];

  if(sizeof($v['existing_files'])) {
            foreach($v['existing_files'] as $fid){
                if(is_numeric($fid)){
                    db_query("INSERT IGNORE {upload}(fid, nid, vid, description,list) VALUES(%d, %d, %d, '%s', 0)",$fid, $values['values']['nid'], $values['values']['vid'], t('File !d', array('!d'=>$fid)));
                }else{//First save the file to the files table befure adding it to the uploads table
                    $extensions = '';
                    foreach ($user->roles as $rid => $name) {
                      $extensions .= ' '. variable_get("upload_extensions_$rid",

                      variable_get('upload_extensions_default', 'jpg jpeg gif png txt html doc xls pdf ppt pps odt ods odp'));
                    }
                    $file = new stdClass();
                    $file->uid = $user->uid;
                    $file->filename = file_munge_filename(trim(basename($fid), '.'), $extensions);
                    $file->filepath = $fid;
                    $file->filemime = fn_mime_content_type($fid); //Note that this function has been deprecated in favor of the PECL extension Fileinfo
                    $file->filesize = filesize($fid);
                    $file->status = 1; //A permanent file
                    $file->timestamp = time();
                    
                    drupal_write_record("files", $file);
                    db_query("INSERT IGNORE {upload}(fid, nid, vid, description,list) VALUES(%d, %d, %d, '%s', 1)",$file->fid, $values['values']['nid'], $values['values']['vid'], '');
                }
            }
    }
  db_query("DELETE FROM {kgallery_nodes} WHERE vid=%d", $v['vid']);
  $tuples = array();
  foreach($v['media']['mids'] as $mid => $info) {
    $tuples[] = sprintf('(%d, %d)', $v['vid'], $mid);
  }
  db_query("INSERT INTO {kgallery_nodes}(vid, mid) VALUES %s",
            join(',', $tuples));
  _kentry_update_cache($node);
}


/**
 * Return existing media form
 */
function _existing_media($state, $node) {
  $form = $types = array();
  $form['attachments'] = array(
    '#prefix' => '<div id="attachments">',
    '#suffix' => '</div>',
  );
  $form['attachments']['wrapper'] = array(
    '#prefix' => '<div id="attach-wrapper">',
    '#suffix' => '</div>',
  );
  $form['attachments']['wrapper'] += _upload_form($node);
  $form['#attributes']['enctype'] = 'multipart/form-data';
  foreach(variable_get('kgallery_nodetypes', array()) as $nodetype=>$nodename){
    if($nodename!='0'){		
		}
	}  
	foreach($node->files as $mid=>$include){  
               /* $form[$include->filemime]['title'][$mid] = array('#type'=>'fieldset',
                                                                 '#title'=>$include->filename.'('.t('File !d', array('!d'=>$include->fid)).')',
                                                                 '#description'=>$include->description.' '.l(t('Add metadata such as captions to this file'), 'kfile/'.$include->fid.'/edit', array('query'=>'destination=node/'.$node->nid)),
                                                                 '#collapsed'=>TRUE,
                                                                 '#collapsible'=>TRUE);*/
	}
        
	$form['nid'] = array('#type'=>'value', '#value'=>$node->nid);
  $form['submit'][] = 'upload_form_submit';
  return $form;
}


function kgallery_settings(){
    $types = node_get_types('names');
    $form = array();
    
    $form['access'] = array(
            '#type' => 'fieldset',
            '#title' => t('Access control').t(': Show/Hide'),
            '#collapsible'=>TRUE,
        );
    $form['access']['kgallery_allow_all'] = array(
            '#type' => 'radios',
            '#title' => t('Allow all IP addresses'),
            '#options' => array(1=>t('Yes'), 0=>t('No')),
            '#default_value'=>variable_get('kgallery_allow_all', 1),
            '#description' => t('Which IP addresses can access
                    /node/<xxx>/files URLs? Separate by commas, no newlines
                    or spaces allowed')
        );
    $form['access']['kgallery_allowed_ips'] = array(
            '#type' => 'textarea',
            '#title' => t('Allowed IP addresses'),
            '#default_value'=>variable_get('kgallery_allowed_ips',
                                           $_SERVER['SERVER_ADDR']),
            '#description' => t('Which IP addresses can access
                    /node/<xxx>/files URLs? Separate by commas, no newlines
                    or spaces allowed')
        );
    
    $form['node'] = array(
            '#type' => 'fieldset',
            '#title' => t('Configure Media Gallery').t(': Show/Hide'),
            '#collapsible'=>TRUE,
        );
   
    
    $form['node']['kgallery_nodetypes'] = array(
                                    '#type'=>'checkboxes',
                                    '#title' => 'Display the media gallery on',
                                    '#options'=>$types,
                                    '#default_value'=>variable_get('kgallery_nodetypes', array())
                            );
    $form['node']['kgallery_view_offset'] = array(
                                    '#type'=>'textfield',
                                    '#title'=>t('Gallery position'),
                                    '#description'=>t('The position of the gallery relative to the node body. Use a negative weight to place it before the node body and a positive weight to place after the node body'),
                                    '#default_value'=>variable_get('kgallery_view_offset', -10)
                            );
    {
    $form['jw'] = array(
            '#type' => 'fieldset',
            '#title' => t('Default JW Media Player Settings').t(': Show/Hide'),
            '#collapsible' => TRUE,
            '#collapsed' => TRUE,
        );
    
    $form['jw']['basics'] = array('#type'=>'fieldset', '#title'=>t('Basics'), '#tree'=>FALSE, '#collapsible'=>TRUE, '#collapsed'=>FALSE);
    $form['jw']['basics']['mplayer'] = array('#tree' =>TRUE);
    $mplayer = variable_get('mplayer', array());
    $form['jw']['basics']['mplayer']['height'] = array(
            '#type' => 'textfield',
            '#title' => t('Height'),
            '#default_value' => isset($mplayer['height'])?$mplayer['height']:312,
            '#description' => t("(number): As with the width of the player/rotator, this variable is already set with a default embed code. However, sometimes (notably on IE), this won't get through (so you get a messed-up display). Then use this flashvar to tell the player/rotator how many pixels high it should be.")
        );
    $form['jw']['basics']['mplayer']['width'] = array(
            '#type' => 'textfield',
            '#title' => t('Width'),
            '#default_value' => isset($mplayer['width'])?$mplayer['width']:300,
            '#description' => t("(number): As with the height of the player/rotator, this variable is already set with a default embed code. However, sometimes (notably on IE), this won't get through (so you get a messed-up display). Then use this flashvar to tell the player/rotator how many pixels wide it should be.")
        );
    $form['jw']['colors'] = array('#type'=>'fieldset', '#title'=>t('Colors'), '#tree'=>FALSE, '#collapsible'=>TRUE, '#collapsed'=>TRUE);
    $form['jw']['colors']['mplayer'] = array('#tree' =>TRUE);
    $form['jw']['colors']['mplayer']['backcolor'] = array(
            '#type' => 'textfield',
            '#title' => t('Backcolor'),
            '#default_value' => isset($mplayer['backcolor'])?$mplayer['backcolor']:'0x000000',
            '#description' => t("(color): Backgroundcolor of the player/rotator. The default for the players is 0xFFFFFF (white) and for the rotator 0x000000 (black)."),
        );
    $form['jw']['colors']['mplayer']['frontcolor'] = array(
            '#type' => 'textfield',
            '#title' => t('Frontcolor'),
            '#default_value' => isset($mplayer['frontcolor'])?$mplayer['frontcolor']:'0xCCCCCC',
            '#description' => t(" (color): Texts / buttons color of the player/rotator. The default for the players is 0x000000 (black) and for the rotator 0xFFFFFF (white)."),
        );
    $form['jw']['colors']['mplayer']['lightcolor'] = array(
            '#type' => 'textfield',
            '#title' => t('Lightcolor'),
            '#default_value' => isset($mplayer['lightcolor'])?$mplayer['lightcolor']:'0x996600',
            '#description' => t("(color): Rollover/ active color of the player/rotator. The default for the players is 0x000000 (black) and for the rotator 0xCC0000 (red)."),
        );
    $form['jw']['colors']['mplayer']['screencolor'] = array(
            '#type' => 'textfield',
            '#title' => t('Lightcolor'),
            '#default_value' => isset($mplayer['screencolor'])?$mplayer['screencolor']:'0x000000',
            '#description' => t("(color): Color of the display area, in HEX format. With the rotator, change this to your HTML page's color to make images of different sizes blend nicely."),
        );
    
    $form['jw']['da'] = array('#type'=>'fieldset', '#title'=>t('Display appearance'), '#tree'=>FALSE, '#collapsible'=>TRUE, '#collapsed'=>TRUE);
    $form['jw']['da']['mplayer'] = array('#tree' =>TRUE);
    $form['jw']['da']['mplayer']['logo'] = array(
            '#type' => 'textfield',
            '#title' => t('Watermark'),
            '#default_value' => isset($mplayer['logo'])?$mplayer['logo']:'',
            '#description' => t("(url): Set this flashvar to put a watermark logo in the top right corner of the display. All image formats are supported, but transparent PNG files give the best results."),
        );
    $form['jw']['da']['mplayer']['overstretch'] = array(
            '#type' => 'textfield',
            '#title' => t('Stretch'),
            '#default_value' => isset($mplayer['overstretch'])?$mplayer['overstretch']:'false',
            '#description' => t("(false): Sets how to stretch images/movies to make them fit the display. The default stretches to fit the display. Set this to true to stretch them proportionally to fill the display, fit to stretch them disproportionally and none to keep original dimensions."),
        );
    $form['jw']['da']['mplayer']['showicons'] = array(
            '#type' => 'textfield',
            '#title' => t('Icons'),
            '#default_value' => isset($mplayer['showicons'])?$mplayer['showicons']:'true',
            '#description' => t("(true): Set this to false to hide the activity icon and play button in the middle of the display."),
        );
    $form['jw']['ca'] = array('#type'=>'fieldset', '#title'=>t('Controlbar appearance'), '#tree'=>FALSE, '#collapsible'=>TRUE, '#collapsed'=>TRUE);
    $form['jw']['ca']['mplayer'] = array('#tree' =>TRUE);
    $form['jw']['ca']['mplayer']['shownavigation'] = array(
            '#type' => 'textfield',
            '#title' => t('Navigation'),
            '#default_value' => isset($mplayer['shownavigation'])?$mplayer['shownavigation']:'false',
            '#description' => t("(false): Set this to false to completely hide the controlbar."),
        );
    $form['jw']['ca']['mplayer']['showstop'] = array(
            '#type' => 'textfield',
            '#title' => t('Stop button'),
            '#default_value' => isset($mplayer['showstop'])?$mplayer['showstop']:'false',
            '#description' => t("(false): Set this to true to show a stop button in the controlbar."),
        );
    $form['jw']['ca']['mplayer']['showdigits'] = array(
            '#type' => 'textfield',
            '#title' => t('Time indicator'),
            '#default_value' => isset($mplayer['showdigits'])?$mplayer['showdigits']:'true',
            '#description' => t("(true): Set this to false to hide the elapsed/remaining digits in the controlbar."),
        );
    
    $form['jw']['ca']['mplayer']['showdownload'] = array(
            '#type' => 'textfield',
            '#title' => t('Downloadable'),
            '#default_value' => isset($mplayer['showdownload'])?$mplayer['showdownload']:'false',
            '#description' => t("(false): Set this to true to show a button in the player controlbar which links to the link flashvar."),
        );
    $form['jw']['ca']['mplayer']['usefullscreen'] = array(
            '#type' => 'textfield',
            '#title' => t('Full screen'),
            '#default_value' => isset($mplayer['usefullscreen'])?$mplayer['usefullscreen']:'true',
            '#description' => t("(true): Set this to false to hide the fullscreen button and disable fullscreen."),
        );
    $form['jw']['ca']['mplayer']['largecontrols'] = array(
            '#type' => 'textfield',
            '#title' => t('Largecontrols'),
            '#default_value' => isset($mplayer['largecontrols'])?$mplayer['largecontrols']:'false',
            '#description' => t("(true,false): Set this to true to make the controlbar twice as large. This is useful to visually impaired users."),
        );
    $form['jw']['pa'] = array('#type'=>'fieldset', '#title'=>t('Playlist appearance'), '#tree'=>FALSE, '#collapsible'=>TRUE, '#collapsed'=>TRUE);
    $form['jw']['pa']['mplayer'] = array('#tree' =>TRUE);
    $form['jw']['pa']['mplayer']['displayheight'] = array(
            '#type' => 'textfield',
            '#default_value' => isset($mplayer['displayheight'])?$mplayer['displayheight']:312,
            '#title' => t('Display Height'),
            '#description' => t('(number): This flashvar is used by the players and sets the height of the display. It defaults to the height of the SWF object minus the controlbar (20px), but if you set it to a smaller height, the playlist will show up. If you set it to the height of the player itself (or larger), the controlbar will auto-hide over the video.')
        );
    $form['jw']['pa']['mplayer']['displaywidth'] = array(
            '#type' => 'textfield',
            '#default_value' => isset($mplayer['displaywidth'])?$mplayer['displaywidth']:312,
            '#title' => t('Display Width'),
            '#description' => t('(number of pixels): Instead of the "displayheight", you can set "displaywidth" to a size smaller that the SWF width to make the playlist appear at the right side of the display.')
        );
    
    $form['jw']['pa']['mplayer']['autoscroll'] = array(
            '#type' => 'textfield',
            '#title' => t('Autoscroll'),
            '#default_value' => isset($mplayer['autoscroll'])?$mplayer['autoscroll']:'true',
            '#description' => t('(true,false): By default, the playlist area of the players will have a scrollbar if the number of items is too long. If you set this flashvar to "true", the scrollbar wil disappear and the playlist will scroll automatically, depending upon the mouse position.')
        );
    $form['jw']['pa']['mplayer']['thumbsinplaylist'] = array(
            '#type' => 'textfield',
            '#title' => t('Playlist thumbnails'),
            '#default_value' => isset($mplayer['thumbsinplaylist'])?$mplayer['thumbsinplaylist']:'true',
            '#description' => t('(true): Set this to false to hide preview images in the display (and restrict the buttons to a single line).')
        );
    
    $form['jw']['pb'] = array('#type'=>'fieldset', '#title'=>t('Playback behaviour'), '#tree'=>FALSE, '#collapsible'=>TRUE, '#collapsed'=>TRUE);
    $form['jw']['pb']['mplayer'] = array('#tree' =>TRUE);
    $form['jw']['pb']['mplayer']['autostart'] = array(
            '#type' => 'textfield',
            '#title' => t('Autostart'),
            '#default_value' => isset($mplayer['autostart'])?$mplayer['autostart']:'false',
            '#description' => t('(true,false,muted): Set this to "true" to make the player automatically start playing when the page loads. If set to "muted", the player will autostart with the volume set to 0 and an unmute icon in the display.'),
        );
    $form['jw']['pb']['mplayer']['bufferlength'] = array(
            '#type' => 'textfield',
            '#title' => t('Bufferlength'),
            '#default_value' => isset($mplayer['bufferlength'])?$mplayer['bufferlength']:'3',
            '#description' => t("(number): This sets the number of seconds an FLV should be buffered ahead before the player starts it. Set this smaller for fast connections or short videos. Set this bigger for slow connections. The default is 3 seconds."),
        );
    $form['jw']['pb']['mplayer']['repeat'] = array(
            '#type' => 'textfield',
            '#title' => t('Repeat'),
            '#default_value' => isset($mplayer['repeat'])?$mplayer['repeat']:'list',
            '#description' => t('(true,false,list): By default, the players will stop playback after every item to preserve bandwidth (repeat=false). You can set this to "list" to playback all items in a playlist once, or to "true" to continously playback your song/movie/playlist.'),
        );
    $form['jw']['pb']['mplayer']['rotatetime'] = array(
            '#type' => 'textfield',
            '#title' => t('Image playback time'),
            '#default_value' => isset($mplayer['rotatetime'])?$mplayer['rotatetime']:'5',
            '#description' => t('(5): Sets the number of seconds an image is played back.'),
        );
    $form['jw']['pb']['mplayer']['shuffle'] = array(
            '#type' => 'textfield',
            '#title' => t('Shuffle'),
            '#default_value' => isset($mplayer['shuffle'])?$mplayer['shuffle']:'true',
            '#description' => t('(true): Set this to false to playback a playlist sequentially (first to last) instead of shuffled.'),
        );
    $form['jw']['pb']['mplayer']['volume'] = array(
            '#type' => 'textfield',
            '#title' => t('Initial volume'),
            '#default_value' => isset($mplayer['volume'])?$mplayer['volume']:'80',
            '#description' => t('(number): sets the startup volume for playback of sounds, movies and audio tracks.'),
        );
    $form['jw']['pb']['mplayer']['callback'] = array(
            '#type' => 'textfield',
            '#title' => t('Callback'),
            '#default_value' => isset($mplayer['callback'])?$mplayer['callback']:'urchin',
            '#description' => t('Set this to a serverside script that can process statistics. The player will send it a POST every time an item starts/stops. To send callbacks automatically to Google Analytics, set this to urchin (if you use the old urchinTracker code) or analytics (if you use the new pageTracker code).'),
        );
    }
    
        $form['file'] = array(
            '#type' => 'fieldset',
            '#title' => t('Default Playlist Data').t(': Show/Hide'),
            '#collapsible' => TRUE,
            '#collapsed' => TRUE,
        );
    $form['file']['xspf_playlist_metadata'] = array(
            '#type' => 'textfield',
            '#title' => t('File metadata fields'),
            '#default_value' => variable_get('xspf_playlist_metadata', 'textfield#>caption#>Subtitle Captions'),
            '#description' => t('Create extra fields for entering extra information about the database entry, e.g. textfield#>pron#>Pronunciation, textfield#>slang#>Slang, textfield#>d1#>Dialect 1, textfield#>d2#>Dialect 2,  etc, in the format FIELDTYPE#>NAME#>TITLE. Separate each field with a comma.'),
            
        );
    /*
    $form['xpsf_playlist_captions'] = array(
            '#type' => 'textfield',
            '#title' => t('Iframe target'),
            '#description' => t('(_parent, _kDP): Use _parent to open in the same window. Use _kDP to open in a separate window.'),
            '#default_value' => variable_get('iframe_target', '_kDP'),
        );
    */
    $form['file']['xspf_playlist_title'] = array(
        '#type' => 'textfield',
        '#title' => t('Playlist title'),
        '#default_value' => variable_get('xspf_playlist_title', t('%sitename playlist', array('%sitename' =>  variable_get('site_name', 'Drupal')))),
        '#description' => t('Displayed on playlist.'),
      );
          
    $form['file']['xspf_playlist_info'] = array(
      '#type' => 'textfield',
      '#title' => t('Playlist info'),
      '#default_value' => variable_get('xspf_playlist_info', ''),
      '#description' => t('Information about this playlist. Some players will display this information')
    );
    
    $form['file']['xspf_filetype'] = array(
      '#type' => 'textfield',
      '#title' => t('File type support'),
      '#default_value' => variable_get('xspf_filetype', 'flv,jpg,gif,png,mp3'),
      '#description' =>t('Will only use attached files of these file types. Comma seperated list, avoid spaces.'),
    );


    $height = variable_get("kgallery_thumb_height", 200);
    $width = variable_get("kgallery_thumb_width", 200);
    $align = variable_get("kgallery_thumb_align", 'left');
    $form['thumb'] = array(
            '#type' => 'fieldset',
            '#title' => t('Thumbnail'),
            '#collapsible'=>TRUE,
        );
    $form['thumb']['xspf_playlist_thumb'] = array(
      '#type' => 'textfield',
      '#title' => t('Default thumbnail for playlist items'),
      '#default_value' => variable_get('xspf_playlist_thumb', ''), 
      '#description' =>t('Path to your default image, requires http://mydomain.com/ . If you change this, you must save this page before the changes are available to the settings below.'),
    );
    $form['thumb']['kgallery_thumb_width'] = array(
            '#type' => 'textfield',
            '#title' => t('Width'),
            '#description' => t('The width of the default thumbnail image'),
            '#default_value' => $width,
        );
    $form['thumb']['kgallery_thumb_height'] = array(
            '#type' => 'textfield',
            '#title' => t('Height'),
            '#description' => t('The height of the default thumbnail image'),
            '#default_value' => $height,
        );
    
    $form['thumb']['kgallery_thumb_align'] = array(
            '#type' => 'textfield',
            '#title' => t('Alignment'),
            '#description' => t('The alignment of the default thumbnail image'),
            '#default_value' => $align,
        );
    $form['thumb']['kgallery_thumb_mapspan'] = array(
            '#type' => 'textfield',
            '#title' => t('Google Map span'),
            '#description' => t('Comma-separated span. e.g., <i>10,10</i>. '.
                                'Note that there should be no space after the '.
                                'comma'),
            '#default_value' => variable_get('kgallery_thumb_mapspan', '10,10'),
        );
    $form['card'] = array(
            '#type' => 'fieldset',
            '#title' => t('Greeting Cards'),
            '#collapsible'=>TRUE,
        );
    $form['card']['font_directory_path'] = array('#type' => 'textfield',
        '#title' => t('Font directory'),
        '#default_value' => variable_get('font_directory_path', '.'),
        '#size' => 60,
        '#maxlength' => 128,
        '#description'=>t('Directory containing fonts for writing greeting cards'),
        );
    $form['card']['kgreeting_default_font'] = array('#type' => 'textfield',
        '#title' => t('Default font'),
        '#default_value' => variable_get('kgreeting_default_font', 'ARIALUNI.TTF'),
        '#size' => 60,
        '#maxlength' => 128,
        '#description'=>t('Relative to the directory containing fonts for writing greeting cards: %path', array('%path'=>variable_get('font_directory_path', '.')."/")),
        );
    
    $options = array();
    if(module_exists('taxonomy')){
       $vocabs = taxonomy_get_vocabularies();
       $options = array();
       foreach($vocabs as $vid=>$vocab){
          $options[$vid] = $vocab->name;
       }
    }
    $form['card']['postcard_vid'] = array(
        '#type' => 'select',
        '#multiple' => false,
        '#title' => t('Taxonomy'),
        '#default_value' => variable_get('postcard_vid', 0),
        '#options' => $options,
        '#description' => t('Select the vocabulary used to organize the postcard gallery.'),
      );
    $types[-1] = t('None');
    $form['card']['postcard_node'] = array(
        '#type' => 'select',
        '#multiple' => false,
        '#title' => t('Node used for greeting cards'),
        '#default_value' => variable_get('postcard_node', 0),
        '#options' => $types,
        '#description' => t('Select the node used to create postcards.'),
      );
    
    $form['card']['kgreeting_preview_w'] = array('#type' => 'textfield',
        '#title' => t('Default preview width'),
        '#default_value' => variable_get('kgreeting_preview_w', 520),
        '#size' => 60,
        '#maxlength' => 128,
        '#description'=>'',
        );
    $form['card']['kgreeting_preview_h'] = array('#type' => 'textfield',
        '#title' => t('Default preview height'),
        '#default_value' => variable_get('kgreeting_preview_h', 320),
        '#size' => 60,
        '#maxlength' => 128,
        '#description'=>'',
        );
    $form['card']['kgreeting_thumb_w'] = array('#type' => 'textfield',
        '#title' => t('Default thumbnail width'),
        '#default_value' => variable_get('kgreeting_thumb_w', $width),
        '#size' => 60,
        '#maxlength' => 128,
        '#description'=>'',
        );
    $form['card']['kgreeting_thumb_h'] = array('#type' => 'textfield',
        '#title' => t('Default thumbnail height'),
        '#default_value' => variable_get('kgreeting_thumb_w', $height),
        '#size' => 60,
        '#maxlength' => 128,
        '#description'=>'',
        );
    $form['card']['kgreeting_themes'] = array('#type' => 'textarea',
        '#title' => t('Available themes'),
        '#default_value' => variable_get('kgreeting_themes', ''),
        '#description'=>'Put one theme on each line. Separate the theme properties with a "#>" symbol',
        );
    $form['content'] = array(
        '#type' => 'fieldset',
        '#title' => t('Content settings'),
        '#collapsible' => TRUE,
      );
  
  $enabled_types = variable_get('xspf_playlist_types', array());
  $form['content']['xspf_playlist_types'] = array(
   '#type' => 'checkboxes',
   '#title' => t('Enable playlist on'),
   '#description' => t('Choose which content types you want to be able to use playlists on.'),
   '#options' => $types,
   '#default_value' => $enabled_types,
  );
  
  if ($enabled_types) {
    foreach ($enabled_types as $name => $value) {
      if ($value) {
        // create content type field set
        $form['content']['thetype_'. $value] = array(
          '#type' => 'fieldset',
          '#title' => t('!type settings', array('!type' => $types[$value])).t(': Show/Hide'),
          '#collapsible'=>TRUE,
          '#collapsed' => TRUE,
        );
        
        // use attached files
        if (module_exists('upload')) {
          $form['content']['thetype_'. $value]['xspf_'. $value .'_files'] = array(
            '#type' => 'checkbox',
            '#title' => t('Use attached files for the play list'),
            '#default_value' => variable_get('xspf_'. $value .'_files', ''),
            '#description' => t('If this is checked, all attached media files will be added to the playlist.'),
          );
        }
        
        //Use kasahorow data type fields
        if(module_exists('kentry')){
            $iso = $value;
            //Allow the default thumbnail for this node type to be specified
            //on the node itself
            $chn = array();
            $field_names = array();
            $cq = db_query("SELECT * FROM {kentry_fields}
                    WHERE iso='%s' AND ftype IN ('textfield', 'hidden', 'url')
                  ORDER BY category, weight, name", $iso);
            while($r = db_fetch_object($cq)){
                $chn[$r->kfid] = $r;
                $field_names[$r->kfid] = $r->label;
            }
            if(count($chn)){
                // build the form
                $form['content']['thetype_'. $value]['xspf_playlist_'. $value .'_fields' ] = array(
                    '#title' => t('%name', array('%name' => $title)),
                    '#type' => 'checkboxes',
                    '#options' => $field_names,              
                    '#title' => t('Use this field'),
                    '#description' => t('On an enabled field, this module will try to find a file path and if so, add it to the playlist. This module will search the field for the first http:// and use this url as the file path.'),
                    '#default_value' => variable_get('xspf_playlist_'. $value .'_fields', array()),
                  );
            }
          }
          
          // build the default options for the thumbnail list
          
          $defaults[t('Automatic')]['-card-'] = t('Greeting card thumbnail
                                        (slow on pages with several nodes)');
          if (variable_get('xspf_playlist_thumb', '') ) { 
            $defaults[t('Automatic')]['xspf_default'] = t('Default thumbnail');
          }
          // merge with the field list
          $default_field = array_merge($defaults,
                                is_array($field_names)
                                ?
                                array(t('Use field value')=>$field_names)
                                :
                                array());
          
        $form['content']['thetype_'. $value]['xspf_'. $value .'_thumb' ] =
            array(
                '#title' => t('Default thumbnail field'), 
                '#type' => 'select',
                '#options' => $default_field,
                '#default_value' => variable_get('xspf_'. $value .'_thumb', ''),
                '#description' => t('Use this as thumbnail. Use \'none\' for no default, \'Default thumbnail\' for the default thumbnail entered above (only available if it has already been saved), \'first image\' for the first available image attached to the entry, or choose a field to select from. If a kasahorow data type field is choosen, but no data exists there, this will attempt to use the default value if set.'),
              );
        
        $form['content']['thetype_'. $value]['xspf_'. $value .'_caption' ] = array(
            '#title' => t('Default captions field'), 
            '#type' => 'select',
            '#options' => $default_field,
            '#default_value' => variable_get('xspf_'. $value .'_caption', ''),
            '#description' => t('Use this as the default captions field if captions are not specified for the file being played. Use \'none\' for no default, \'Default caption\' for the default thumbnail entered above (only available if it has already been saved), or chose a field to select from. If a kasahorow data type field is choosen, but no data exists there, this will attempt to use the default value if set.'),
          );
      }
    }
  }
  return system_settings_form($form);
}


function _ui_kgallery_manager() {
  $form = drupal_get_form('kgallery_form');
  $db = new KDatabase('kgallery');
  $rows = $db->RetrieveRows(array('wheres' => array(), 'debug' => 0));
  $media = array();
  foreach($rows as $r) {
    $media[] = array(
      l($r->name, 'admin/content/kw/kgallery/view/'.$r->mid),
      sprintf('<%s width="120" height="100" controls></%s>', $r->type, $r->type),
    );
  }
  $output = theme('table', array('File', 'Preview'), $media, array('width'=> '100%')).theme('pager');
  return $form.$output;
}

/**
 * Add a new file to the gallery.
 */
function _kgallery_add($url, $type, $name, $uid=0, $mid=NULL) {
  if($mid) {
    db_query("UPDATE {kgallery} SET type='%s', name='%s', url='%s', uid=%d
              WHERE mid=%d", $type, $name, $url, $uid, $mid);
  }else {
    db_query("insert into {kgallery}(type, name, url, uid) 
              VALUES('%s', '%s', '%s', %d)",
              $type, $name, $url, $uid);
    $mid = db_last_insert_id('kgallery', 'mid');
  }
  return $mid;
}

/**
 * Retrieve a gallery entry given the primary key
 */
function _kgallery_get($mid) {
  return db_fetch_object(db_query("SELECT * FROM {kgallery} WHERE mid=%d", $mid)); 
}

function kgallery_form($state, $media=NULL) {
  $form = array();
  $form['url'] = array(
    '#default_value' => $media->url,
    '#title' => 'URL',
    '#type' => 'textfield',
    '#description' => 'URL of media file',
    '#required' => True,
  );
  $form['type'] = array(
    '#type' => 'select',
    '#title' => 'Media type',
    '#options' => array('' => '--Select--', 'audio' => 'Audio', 'video' => 'Video', 'img' => 'Photo'),
    '#required' => True,
    '#default_value' => $media->type,
  );
  $form['name'] = array(
    '#title' => 'Name',
    '#type' => 'textfield',
    '#description' => 'Name to be used in media player',
    '#required' => True,
    '#default_value' => $media->name,
  );
  $form['mid'] = array('#type' => 'hidden', '#value' => $media->mid);
  $form['submit'] = array('#type'=>'submit', '#value'=>t('Save changes'));
  return $form;
}

function kgallery_form_submit($state, &$values) {
  drupal_set_message('File added');
  $v = $values['values'];
  _kgallery_add($v['url'], $v['type'], $v['name'], $v['uid'], $v['mid']);
}

function _ui_kgallery_view_file($mid) {
  $media = _kgallery_get($mid);
  drupal_set_title($media->name);
  if($media->type == 'img') {
    $preview = sprintf('<img src="%s" />', $media->url);
  }else {
    $preview = sprintf('<%s controls><souce src="%s"></%s>',
                        $media->type, $media->url, $media->type);
  }
  
  $output = l(t('Media gallery'), 'admin/content/kw/kgallery');
  $output.= '<div class="preview">'.$preview.'</div>';
  $output.= drupal_get_form('kgallery_form', $media);
  $output.= _kgallery_nodes($media->mid);
  return $output;
}

function _kgallery_nodes($mid) {
  return 'TODO: List of nodes with this file in it';  
}

function _kgallery_load($vid) {
  $db = new KDatabase('kgallery');
  $rows = $db->RetrieveRows(array('wheres' => array(), 'debug' => 0));
  $media = array();
  foreach($rows as $r) {
    $media[ucfirst($r->type)][$r->mid] = $r->name;
  }  
  return $media;
}
